<template>
  <div>
    <section class="todoapp">
      <header>
        <!-- 这里，将h1作为默认插槽（非具名）传进来 -->
        <slot></slot>
        <input
          v-model="currentTitle"
          autofocus="autofocus"
          autocomplete="off"
          placeholder="What needs to be done?"
          class="new-todo"
          @keypress.enter="addTask"
        />
      </header>
      <section class="main">
        <input
          type="checkbox"
          id="toggle-all"
          class="toggle-all"
          @change="toggleAll"
          :checked="isAllCompleted"
        />
        <label for="toggle-all">Mark all as complete</label>
        <ul class="todo-list">
          <!-- 数据通过循环 list 生成 -->
          <li
            :original="original"
            :editing="editing"
            v-for="(todo, index) in list"
            :key="index"
            class="todo"
            :class="{
              completed: todo.isCompleted,
              editing: index === editing.index,
            }"
          >
            <div class="view">
              <!-- 通过v-model将 checkbox 的值和 todo.isCompleted 进行绑定，点击后会自动修改 todo.isCompleted 的值，反之亦然 -->
              <input
                type="checkbox"
                class="toggle"
                v-model="todo.isCompleted"
              />
              <label @dblclick="edit(index)">{{ todo.title }}</label>
              <button class="destroy" @click="removeTodo(index)"></button>
            </div>
            <!--
              编辑todo的需求：
              1. 按下回车可以保存；
              2. 按下esc取消编辑，并恢复之前的值；
              3. 失去焦点时保存
            -->
            <input
              v-todo-focus="index === editing.index"
              type="text"
              class="edit"
              :value="editing.title"
              @blur="save"
              @keyup.enter="save"
              @keyup.esc="cancelEdit"
            />
          </li>
        </ul>
      </section>
      <footer class="footer">
        <span class="todo-count">
          <!-- 此处显示的是，没有打钩（没有完成）的任务数 -->
          <strong>{{ incomplete.length }}</strong>
          item{{ incomplete.length > 1 ? 's' : '' }} left
        </span>
        <ul class="filters">
          <li>
            <router-link :class="{ selected: this.state === 'all' }" to="/todo"
              >All</router-link
            >
          </li>
          <li>
            <router-link
              :class="{ selected: this.state === 'active' }"
              to="/todo/active"
              >Active</router-link
            >
          </li>
          <li>
            <router-link
              :class="{ selected: this.state === 'completed' }"
              to="/todo/completed"
              >Completed</router-link
            >
          </li>
        </ul>
        <button class="clear-completed" @click="removeDone">
          Clear completed
        </button>
      </footer>
    </section>
  </div>
</template>

<script>
export default {
  name: 'todo-list',
  //props为了将TodoList中拿到的数据传给todo-list
  props: {
    original: {
      type: Array,
      required: true,
    },

    editing: {
      type: Object,
      required: true,
    },

    list: {
      type: Array,
      requred: true,
    },
  },
  data() {
    return {
      currentTitle: '',
    };
  },
  methods: {
    toggle(todo) {
      todo.isCompleted = !todo.isCompleted;
    },
    toggleAll() {
      const isAllCompleted = this.isAllCompleted;
      this.original.forEach(todo => {
        todo.isCompleted = !isAllCompleted;
      });
    },
    addTask() {
      this.$store.dispatch('todoModule/createTodo', this.currentTitle);
      // 需要清空输入框（因为这里双向绑定了数据，所以只要清空了变量就可以了）
      this.currentTitle = '';
      // }
    },
    removeTodo(index) {
      this.list = this.original;
      this.$store.dispatch('todoModule/removeTodo', index);
    },
    edit(todoIndex) {
      this.$store.dispatch('todoModule/editTodo', todoIndex);
      // this.editing.index = todoIndex;
      // this.editing.title = this.list[todoIndex].title;
    },
    cancelEdit() {
      this.$store.dispatch('todoModule/canceleditTodo');
      // this.editing.index = -1;
    },
    save(e) {
      // inputValue 是这个文本框中的当前文本，也就是需要保存的文本
      const inputValue = e.target.value.trim();

      // 解构赋值，等同于 const index = this.editing.index
      const { index } = this.editing;
      // index = -1 表示现在不在编辑状态
      if (inputValue && index !== -1) {
        this.original[index].title = inputValue;
      }
      // 取消编辑状态
      this.cancelEdit();
    },
    removeDone() {
      this.$store.dispatch('todoModule/removedoneTodo');
    },
  },
  computed: {
    isAllCompleted() {
      return this.original.every(todo => todo.isCompleted);
    },
    incomplete() {
      return this.original.filter(todo => !todo.isCompleted);
    },
    state() {
      return this.$route.params.state || 'all';
    },
  },
  directives: {
    todoFocus(el, binding) {
      // 指令，用于input获取焦点。如果使用autofocus属性，只有dom节点在第一次出现时会被触发，后来的编辑状态无法再次获取焦点
      // 实际项目中用的较少，稍做了解即可
      if (binding.value) {
        el.focus();
      }
    },
  },
  watch: {
    '$route.params.state': {
      handler() {
        this.$store.dispatch('todoModule/displayType', this.state);
        // switch (value) {
        //   case 'all': {
        //     this.list = this.original;
        //     break;
        //   }
        //   case 'active': {
        //     this.list = this.original.filter(todo => !todo.isCompleted);
        //     break;
        //   }
        //   case 'completed': {
        //     this.list = this.original.filter(todo => todo.isCompleted);
        //     break;
        //   }
        // }
      },
      // 加上 immediate: true 后，会在刚开始就立即执行一次；不加的话，只有路由中state的值有变化后才会执行（初始化时不会执行）
      immediate: true,
    },
  },
};
</script>
